package com.common.base;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record;

public class DatagridController extends BaseController {
	/**
	 * 
	 * 获取每页的数据 创建人：张龙 创建时间：Jun 9, 2017 11:16:35 PM
	 *  修改时间：Jun 9, 2017 11:16:35 PM
	 * 
	 */
	@SuppressWarnings("unchecked")
	public <T> void getPageData() {
		HttpSession session = getSession();
		List<T> data, result;
		String realid, pageindex, pagesize;// datagrid真实id,页码，每页的条数
		Ret ret = new Ret();

		realid = getPara("_realid");
		pageindex = getPara("pageindex");
		pagesize = getPara("pagesize");

		// 从session里面获取到session里面的结果
		data = (List<T>) session.getAttribute(realid);

		int ipageindex = Integer.valueOf(pageindex);
		int ipagesize = Integer.valueOf(pagesize);
		int begin = (ipageindex - 1) * ipagesize;// 开始的索引
		int end = ipageindex * ipagesize;// 结束的索引
		int total = data.size();

		if (begin > total) {
			result = new ArrayList<T>();
		} else {
			if (end > total) {
				end = total;
			}
			result = data.subList(begin, end);
		}
		ret.set("rows", result);
		ret.set("total", total);
		renderJson(ret);
	}

	/**
	 * 
	 * 方法简介:datagrid导出excel格式的文件
	 * <p>
	 * 方法详述
	 * </p>
	 * 
	 * @author 张龙
	 * @throws IOException
	 * @date 创建时间 2015-4-7
	 * @since V1.0
	 */
	public void exportExcelData() throws IOException {
		HttpSession session = getSession();
		Iterator iterator;
		List headList;
		String realid, title;// key是代码，value是汉字标题
		Ret result = new Ret();
		List<Object> data;

		realid = getPara("_realid");// 获取表格的id
		headList = (List) session.getAttribute(realid + "_head");// 获取表格的表头

		data = (List<Object>) session.getAttribute(realid);// 获取表格数据

		if (data == null) {
			data = new ArrayList<Object>();
		}

		title = (String) session.getAttribute(realid + "_title");// 获取表格的标题
		HSSFWorkbook wb = CreateExcel(headList, data, title);// 创建内存excel

		result.set("wb", wb);
		result.set("title", title);
		
		getResponse().setContentType("application/vnd.ms-excel");
		getResponse().setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(title+".xls", "utf-8"));
		OutputStream ouputStream = getResponse().getOutputStream();
		wb.write(ouputStream);
		ouputStream.flush();
		ouputStream.close();
		renderNull();
	}

	/**
	 * 创建内存的excel 方法简介:
	 * <p>
	 * 方法详述
	 * </p>
	 * 
	 * @author 张龙
	 * @date 创建时间 2015-4-7
	 * @since V1.0
	 */
	public HSSFWorkbook CreateExcel(List head, List data, String title) {
		// 第一步，创建一个webbook，对应一个Excel文件
		HSSFWorkbook wb = new HSSFWorkbook();
		// 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
		if(title == null){
			title = "结果";
		}
		HSSFSheet sheet = wb.createSheet(title);
		// 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
		HSSFRow row = sheet.createRow((int) 0);
		// 第四步，创建单元格，并设置值表头 设置表头居中
		HSSFCellStyle style = wb.createCellStyle();
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式

		HSSFCell cell;
		Map temphead;
		Map tempdata= new HashMap<String,Object>();
		String key, value;
		// 构造表头
		for (int i = 0; i < head.size(); i++) {
			temphead = (Map) head.get(i);
			value = getValue(temphead);
			cell = row.createCell((short) i);
			cell.setCellValue(value);
			cell.setCellStyle(style);
		}
		// 构造表数据
		for (int i = 0; i < data.size(); i++) {
			if (data.get(i) instanceof Model) {
				tempdata = com.jfinal.plugin.activerecord.CPI.getAttrs((Model)data.get(i));
			} else if (data.get(i) instanceof Record) {
				tempdata = ((Record)data.get(i)).getColumns();
			}else{
				throw new RuntimeException("不是record 也不是model的数据无法导出");
			}
			row = sheet.createRow((int) i + 1);
			for (int j = 0; j < head.size(); j++) {
				temphead = (Map) head.get(j);
				key = getKey(temphead);
				cell = row.createCell((short) j);
				value = String.valueOf(tempdata.get(key));
				cell.setCellValue(value);
				cell.setCellStyle(style);
			}

		}
		return wb;
	}

	/**
	 * 
	 * 方法简介:获取单键值对的key
	 * <p>
	 * 方法详述
	 * </p>
	 * 
	 * @author 张龙
	 * @date 创建时间 2015-4-7
	 * @since V1.0
	 */
	public String getKey(Map map) {
		Object[] array = map.keySet().toArray();
		return (String) array[0];
	}

	/**
	 * 
	 * 方法简介:获取单键值对的value
	 * <p>
	 * 方法详述
	 * </p>
	 * 
	 * @author 张龙
	 * @date 创建时间 2015-4-7
	 * @since V1.0
	 */
	public String getValue(Map map) {
		Object[] array = map.keySet().toArray();
		return (String) map.get(array[0]);
	}
}
